<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-05-10
 * @Time: 15:22
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： DynamicM.php
 */
namespace app\api\model\dynamic;

use app\api\controller\Stock;
use app\common\utils\DateTimeUtil;
use think\Model;

class DynamicM extends Model {
    protected $table = 'dynamic';
    protected $pk = 'id';

    const TYPE_KANPAN = 1; // 看盘

    // 星期
    public static $week = ['日', '一', '二', '三', '四', '五', '六'];

    /**
     * getAllDynamic
     * 获取全部动态数据
     *
     * @author zhengkai
     * @date 2018-05-10
     *
     * @param int $type 动态类型
     * @param int $uid // 用户id
     * @param int $page 当前页数
     * @param int $limit 每页加载条数
     * @return array
     * @throws \think\exception\DbException
     */
    public static function getAllDynamic($type, $uid, $page=1, $limit=10)
    {
        $data = self::all(function ($query) use ($type, $page, $limit) {
            $query->where('type', $type)
                ->field('id, content, attachment, stock, times, to_char(to_timestamp(times),\'yyyy年MM月dd日\') as date, like_count, like_count_set, comment_count, comment_count_set, share_count, share_count_set')
                ->order('times desc')
                ->page($page, $limit);
        });


        $time = null;
        $count = 0;
        foreach ($data as &$vals) {
            // 附件处理
            $attachment = json_decode($vals['attachment'], true);
            $vals['images'] = $attachment['images']??[];
            $vals['video'] = $attachment['video']??[];
            $vals['audio'] = $attachment['audio']??[];

            // 股票代码
            $stock = isset($vals['stock'])?json_decode($vals['stock'], true):[];
            $stockArr = [];
            foreach ($stock as &$valss) {
                $s = Stock::stockData($valss);
                if ($s) $stockArr[] = $s;

            }
            $vals['stock'] = $stockArr;

            // 发布时间
            $vals['times_at'] = date('H:i', $vals['times']);
            $vals['week'] = '星期'.self::$week[date('w', $vals['times'])];

            $vals['like_count'] = countDataNum($vals['like_count'], $vals['like_count_set']);
            $vals['comment_count'] = countDataNum($vals['comment_count'], $vals['comment_count_set']);
            $vals['share_count'] = countDataNum($vals['share_count'], $vals['share_count_set']);

            $vals['like_status'] = DynamicLike::likeStatus($uid, $vals['id']);
            $vals['share_url'] = ''; // todo 分享链接

            unset($vals['attachment'], $vals['like_count_set'], $vals['comment_count_set'], $vals['share_count_set']);

            // $vals['createdTime'] = DateTimeUtil::format($vals['times']);
            if ($time == $vals['date']) {
                $vals['displayTime'] = false;
                $count++;
            } else {
                $vals['displayTime'] = true;
                $time = $vals['date'];
                $count = 0;
            }

            // unset($vals['createdTime']);
        }

        return $data;

        // 获取所有日期
        /*$dateArr = [];
        foreach ($data as $val) array_push($dateArr, $val['date']);
        $dateList = array_unique($dateArr);*/

        // 按照日期分组重组数据
        /*$list = [];
        foreach ($dateList as $val) {

            $dynamicData = [];
            foreach ($data as $key=>&$vals) if ($vals['date']==$val) $dynamicData[] = $vals;

            foreach ($dynamicData as &$vals) {
                // 附件处理
                $attachment = json_decode($vals['attachment'], true);
                $vals['images'] = isset($attachment['images'])?json_decode($attachment['images'], true):[];
                $vals['video'] = isset($attachment['video'])?json_decode($attachment['video'], true):[];
                $vals['audio'] = isset($attachment['audio'])?json_decode($attachment['audio'], true):[];

                // 股票代码
                $stock = isset($vals['stock'])?json_decode($vals['stock'], true):[];
                $stockArr = [];
                foreach ($stock as &$valss) {
                    $s = Stock::stockData($valss);
                    if ($s) $stockArr[] = $s;

                }
                $vals['stock'] = $stockArr;

                // 发布时间
                $vals['times_at'] = date('H:i', $vals['times']);

                $vals['like_count'] = countDataNum($vals['like_count'], $vals['like_count_set']);
                $vals['comment_count'] = countDataNum($vals['comment_count'], $vals['comment_count_set']);
                $vals['share_count'] = countDataNum($vals['share_count'], $vals['share_count_set']);

                $vals['like_status'] = DynamicLike::likeStatus($uid, $vals['id']);
                $vals['share_url'] = ''; // todo 分享链接

                unset($vals['attachment'], $vals['like_count_set'], $vals['comment_count_set'], $vals['share_count_set']);
            }

            $list[] = [
                'date' => $val,
                'week' => '星期'.self::$week[date('w', strtotime($val))],
                'item' => $dynamicData
            ];
        }*/

        // return $list;
    }

    /**
     * updateCommentCount
     * 更新动态评论总数
     *
     * @author zhengkai
     * @date 2018-05-10
     *
     * @param int $id 动态id
     * @throws \think\exception\DbException
     */
    public static function updateCommentCount($id)
    {
        $data = self::get(['id'=>$id]);
        $data->comment_count = ($data->comment_count+1);
        $data->save();
    }

    /**
     * getSingleDynamic
     * 获取单条动态数据
     *
     * @author zhengkai
     * @date 2018-05-10
     *
     * @param int $id 动态id
     * @param int $uid 用户id
     * @return array|false|object|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getSingleDynamic($id, $uid)
    {
        $data = self::field('*, to_char(to_timestamp(times),\'yyyy年MM月dd日\') as date')->where(['id'=>$id])->find();

        if (!$data) return (object)[];

        // 附件处理
        $attachment = json_decode($data['attachment'], true);
        $data['images'] = $attachment['images']??[];
        $data['video'] = $attachment['video']??[];
        $data['audio'] = $attachment['audio']??[];

        // 股票代码
        $stock = isset($data['stock'])?json_decode($data['stock'], true):[];
        $stockArr = [];
        foreach ($stock as &$valss) {
            $s = Stock::stockData($valss);
            if ($s) $stockArr[] = $s;

        }
        $data['stock'] = $stockArr;

        // 发布时间
        $data['times_at'] = date('H:i', $data['times']);
        $data['week'] = '星期'.self::$week[date('w', $data['times'])];

        $data['like_count'] = countDataNum($data['like_count'], $data['like_count_set']);
        $data['comment_count'] = countDataNum($data['comment_count'], $data['comment_count_set']);
        $data['share_count'] = countDataNum($data['share_count'], $data['share_count_set']);

        $data['like_status'] = DynamicLike::likeStatus($uid, $data['id']);
        $data['share_url'] = ''; // todo 分享链接

        unset($data['attachment'], $data['like_count_set'], $data['comment_count_set'], $data['share_count_set']);

        return $data;
    }

    /**
     * updateLikeCount
     * 更新动态点赞总数
     *
     * @author zhengkai
     * @date 2018-05-10
     *
     * @param int $id 动态id
     * @throws \think\exception\DbException
     */
    public static function updateLikeCount($id, $act)
    {
        $data = self::get(['id'=>$id]);
        switch ($act) {
            case 'plus':
                $data->like_count = ($data->like_count+1);
                break;
            case 'minus':
                $data->like_count = ($data->like_count-1);
                break;
        }

        $data->save();
    }

    /**
     * getLimitDynamic
     * 获取指定条数的动态数据
     *
     * @author zhengkai
     * @date 2018-05-10
     *
     * @param $uid
     * @param int $limit
     * @return DynamicM[]|false
     * @throws \think\exception\DbException
     */
    public static function getLimitDynamic($uid, $limit=3)
    {
        $data = self::all(function ($query) use ($limit) {
            $query->field('id, content, attachment, stock, times, to_char(to_timestamp(times),\'yyyy年MM月dd日\') as date, like_count, like_count_set, comment_count, comment_count_set, share_count, share_count_set')
                ->order('times desc')
                ->limit($limit);
        });

        foreach ($data as &$vals) {
            // 附件处理
            $attachment = json_decode($vals['attachment'], true);
            $vals['images'] = $attachment['images']??[];
            $vals['video'] = $attachment['video']??[];
            $vals['audio'] = $attachment['audio']??[];

            // 股票代码
            $stock = isset($vals['stock'])?json_decode($vals['stock'], true):[];
            $stockArr = [];
            foreach ($stock as &$valss) {
                $s = Stock::stockData($valss);
                if ($s) $stockArr[] = $s;
            }
            $vals['stock'] = $stockArr;

            // 发布时间
            $vals['times_at'] = date('H:i', $vals['times']);
            $vals['week'] = '星期'.self::$week[date('w', $vals['times'])];

            $vals['like_count'] = countDataNum($vals['like_count'], $vals['like_count_set']);
            $vals['comment_count'] = countDataNum($vals['comment_count'], $vals['comment_count_set']);
            $vals['share_count'] = countDataNum($vals['share_count'], $vals['share_count_set']);

            $vals['like_status'] = DynamicLike::likeStatus($uid, $vals['id']);
            $vals['share_url'] = ''; // todo 分享链接

            unset($vals['attachment'], $vals['like_count_set'], $vals['comment_count_set'], $vals['share_count_set']);
        }

        return $data;
    }
}